package com.tbit.uqbike.service.business.impl;

import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.service.base.TokenService;
import com.tbit.uqbike.service.business.PermissionService;
import com.tbit.uqbike.webmanager.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Set;

/**
 * jing首创 自定义权限实现，ss取自SpringSecurity首字母
 *
 * @author jing
 */
@Service("ss")
public class PermissionServiceImpl implements PermissionService {
    /**
     * 所有权限标识
     */
    private static final String ALL_PERMISSION = "*:*";

    private static final String PERMISSION_DELIMETER = ",";

    @Autowired
    private TokenService tokenService;
    @Autowired
    private MenuServiceImpl menuService;

    /**
     * 验证用户是否具备某权限
     *
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    @Override
    public boolean hasPermi(String permission) {
        if (StringUtils.isEmpty(permission)) {
            return false;
        }
        LoginInfo loginInfo = tokenService.getLoginInfo();
        Set<String> perms = menuService.selectMenuPermsByUserId(loginInfo.getAccountUserId());
        if (StringUtils.isNull(perms) || CollectionUtils.isEmpty(perms)) {
            return false;
        }
        return hasPermissions(perms, permission);
    }

    /**
     * 验证用户是否不具备某权限，与 hasPermi逻辑相反
     *
     * @param permission 权限字符串
     * @return 用户是否不具备某权限
     */
    @Override
    public boolean lacksPermi(String permission) {
        return !hasPermi(permission);
    }

    /**
     * 验证用户是否具有以下任意一个权限
     *
     * @param permissions 以 PERMISSION_NAMES_DELIMETER 为分隔符的权限列表
     * @return 用户是否具有以下任意一个权限
     */
    @Override
    public boolean hasAnyPermi(String permissions) {
        if (StringUtils.isEmpty(permissions)) {
            return false;
        }
        LoginInfo loginInfo = tokenService.getLoginInfo();
        Set<String> perms = menuService.selectMenuPermsByUserId(loginInfo.getAccountUserId());
        if (StringUtils.isNull(perms) || CollectionUtils.isEmpty(perms)) {
            return false;
        }
        Set<String> authorities = perms;
        for (String permission : permissions.split(PERMISSION_DELIMETER)) {
            if (permission != null && hasPermissions(authorities, permission)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 判断是否包含权限
     *
     * @param permissions 权限列表
     * @param permission  权限字符串
     * @return 用户是否具备某权限
     */
    @Override
    public boolean hasPermissions(Set<String> permissions, String permission) {
        return permissions.contains(ALL_PERMISSION) || permissions.contains(StringUtils.trim(permission));
    }
}
